package com.sin.j2me.wihd.window;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import com.sin.j2me.common.TextFieldStyles;
import com.sin.j2me.util.AsynchTask;
import com.sin.j2me.wihd.FrameWork;
import com.sin.j2me.wihd.common.Commands;
import com.sin.j2me.wihd.common.Constant;
import com.sin.j2me.wihd.common.Protocol;
import com.sin.j2me.wihd.common.Strings;
import com.sin.j2me.wihd.communi.InterfaceRequest;
import com.sin.j2me.wihd.model.Param;
import com.sin.j2me.wihd.model.Response;

public class SigninWindow extends Window implements CommandListener {
	private Form form = null;
	private TextField username = null;
	private TextField password = null;
	private TextField repassword = null;
	public SigninWindow() {
		this.form = new Form(Strings.signin);
		this.form.addCommand(Commands.back);
		this.form.addCommand(Commands.signin);

		
		username = new TextField(Strings.username, null, Constant.LEN_USERNAME, TextFieldStyles.USERNAME);
		password = new TextField(Strings.password, null, Constant.LEN_PASSWORD, TextFieldStyles.PASSWORD);
		repassword = new TextField(Strings.repassword, null, Constant.LEN_PASSWORD, TextFieldStyles.PASSWORD);
		
		form.append(username);
		form.append(password);
		form.append(repassword);

		form.setCommandListener(this);
	}
	
	public Displayable getWindow() {
		return form;
	}

	public void commandAction(Command cmd, Displayable dis) {
//		System.out.println("Cmd:" + cmd.getLabel());
		if(locked){
			setNotice(Strings.I_LOCKED);
			return;
		}
		if(cmd == Commands.back){
			// Back
			FrameWork.finishWindow(this);
		}
		else if(cmd == Commands.signin){
			// Sign in
			if(username.getString().length()==0){
				setNotice(Strings.N_EMPTY_USERNAME);
				return;
			}
			if(password.getString().length()==0){
				setNotice(Strings.N_EMPTY_PASSWORD);
				return;
			}
			if(!password.getString().equals(repassword.getString())){
				setNotice(Strings.N_EMPTY_PWDNOTEQ);
				return;
			}
			
			lock();
			new AsynchTask(new Runnable() {
				public void run() {
					Param param = new Param();
					param.addPam(Protocol.P_USERNAME, username.getString());
					param.addPam(Protocol.P_PASSWORD, password.getString());
					Response response = InterfaceRequest.getResponse(Protocol.I_SIGNIN, param);
					
					if(response.isOk()){
						FrameWork.finishWindow(SigninWindow.this);
						
						setNotice(Strings.N_SIGNINOK);
					}
					else if(response.getStatus() == Response.FAIL){
						setNotice(response.getString(Protocol.R_INFO));
					}
					else{
						setNotice(Strings.P_NETWORKERR);
					}
					setLock(false);
				}
			});
		}
	}
}
